import {config} from "./config";
const MODEL_STATUS ={
      SUCCESS:'success',
      NONE:'none'
}

App({
  onLaunch: function () {
    // 展示本地存储能力
    let logs = wx.getStorageSync('logs') || []
    wx.setStorageSync('logs', logs)
    let that = this;
    wx.getSystemInfo({
      success:  res=>{
        console.log('手机信息res'+res.model)
        let modelmes = res.model;
        if (modelmes.search('iPhone X') != -1) {
          that.globalData.isIphoneX = true
        }

      }
    })
  },

  logout: function () {
    //移除用户信息
    wx.removeStorage({
      key: 'userInfo',
      success (res) {
        console.log(res)
      }
    })
    this.globalData.userInfo = null
    //移除token
    wx.removeStorage({
      key: 'token',
      success (res) {
        console.log(res)
      }
    })
  },
  onshow: function () {

  },

  // 检查本地 storage 中是否有登录态标识
  checkLoginStatus: function () {
    let that = this;
    let token = wx.getStorageSync('token');
    if (token) {
      // 检查 session_key 是否过期
      wx.checkSession({
        // session_key 有效(为过期)
        success: function () {
          // 直接从Storage中获取用户信息
          let userStorageInfo = wx.getStorageSync('userInfo')
          if (userStorageInfo) {
            //当前页面
            let pages = getCurrentPages()
            let currentPage = pages[pages.length-1]
            currentPage.setData({
              userInfo: userStorageInfo
            })
            console.log(userStorageInfo)
            that.globalData.userInfo = userStorageInfo
          } else {
            that.showInfo('缓存信息缺失');
            console.error('登录成功后将用户信息存在Storage的userStorageInfo字段中，该字段丢失')
          }

        },
        // session_key 过期
        fail: function () {
          // session_key过期
          // that.doLogin();
          //跳转到登陆页面
          wx.navigateTo({
            url: '/pages/login/index'
          })
        }
      });
    } else {
      // 无登录态
      // that.doLogin();
      wx.navigateTo({
        url: '/pages/login/index'
      })
    }
  },

  // 登录动作
  doLogin: function (callback = () => {}) {
    let that = this;
    wx.login({
      success: function (loginRes) {
        if (loginRes.code) {

          wx.getUserInfo({

            withCredentials: true, // 非必填, 默认为true

            success: function (infoRes) {
              console.log(infoRes,'>>>')
              const userInfo = infoRes.userInfo
              // 请求服务端的登录接口
              wx.request({
                url: config.api_blink_url+'/v/wx/login',
                method: 'POST',
                header: {
                  'content-type': 'application/x-www-form-urlencoded'
                },

                data: {
                  code: loginRes.code,                    // 临时登录凭证
                  avatarUrl: userInfo.avatarUrl,
                  nickname: userInfo.nickName,
                  gender: userInfo.gender,
                },

                success: function (res) {
                  console.log('login success');
                  res = res.data;
                  console.log(res)
                  if (res.result == 0) {
                    that.globalData.userInfo = res.userInfo;
                    wx.setStorageSync('userInfo', JSON.stringify(res.userInfo));
                    wx.setStorageSync('token', res.token);
                    callback();
                  } else {
                    this.showInfo('抱歉出现了一个错误');
                  }
                },

                fail: function (error) {
                  // 调用服务端登录接口失败
                  that.showInfo('抱歉出现了一个错误');
                  console.log(error);
                }
              });
            },

            fail: function (error) {
              // 获取 userInfo 失败，去检查是否未开启权限
              wx.hideLoading();
              that.checkUserInfoPermission();
            }
          });

        } else {
          // 获取 code 失败
          that.showInfo('登录失败');
          console.log('调用wx.login获取code失败');
        }
      },

      fail: function (error) {
        // 调用 wx.login 接口失败
        that.showInfo('抱歉出现了一个错误');
        console.log(error);
      }
    });
  },

  // 检查用户信息授权设置
  checkUserInfoPermission: function (callback = () => { }) {
    wx.getSetting({
      success: function (res) {
        if (!res.authSetting['scope.userInfo']) {
          wx.openSetting({
            success: function (authSetting) {
              console.log(authSetting)
            }
          });
        }
      },
      fail: function (error) {
        console.log(error);
      }
    });
  },

  // 获取用户登录标示 供全局调用
  getLoginFlag: function () {
    return wx.getStorageSync('token');
  },

  // 封装 wx.showToast 方法
  showInfo: function (info = 'error', icon = 'none') {
    wx.showToast({
      title: info,
      icon: icon,
      duration: 1500,
      mask: true
    });
  },

  globalData: {
    userInfo: wx.getStorageSync('userInfo'),
    isIphoneX: false,
  },
  showModel:function (msg) {
    wx.showToast({
      title:msg,
      icon: 'none',
      duration: 2000
    })
  },
  _LoadMore(array,data) {
    const tempArray = array.concat(data)
    return tempArray
  },
})
